package com.itheima.listener;

import com.alibaba.fastjson.JSON;
import com.itheima.domain.MoneyLog;
import com.itheima.service.MoneyLogService;
import com.itheima.service.RedPacketService;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;

/*****
 * @Author: http://www.itheima.com
 * @Description: com.itheima.listener.MoneyListener
 ****/
@Component
public class MoneyListener {

    @Autowired
    private RedPacketService redPacketService;

    @Autowired
    private  RabbitTemplate rabbitTemplate;

    @Autowired
    private MoneyLogService moneyLogService;

    /****
     * 消息监听，实现抢红包操作
     * @param message
     */
    @RabbitListener(queues = {"red.queue"})
    public void moneyList(String message){
        //1.解析数据
        Map<String,String> userMap = JSON.parseObject(message,Map.class);
        //2.获取user
        String username = userMap.get("user");
        //3.抢红包
        Double money = redPacketService.grab();
        if(money!=null && money>0){
            //抢红包成功-记录数据库
            moneyLogService.add(new MoneyLog(money,username));
        }
        //4.通知用户
        Map<String,Object> messageMap = new HashMap<String,Object>();
        messageMap.put("user",username);
        messageMap.put("money",money);
        messageMap.put("code",(money==null || money<=0)? 204:200);
        rabbitTemplate.convertAndSend("","redmessage.queue",JSON.toJSONString(messageMap));
    }
}
